/***********************************************************
 * Author: 	Brandon McKune
 * E-Mail:	bmckune.cs@gmail.com
 * Date:	September 2, 2011
 * Class:	CSc 8370 - Data Security
 * Time:	1150 - 1325
 * Smstr:	Fall 2011
 */

#include "rc4KeyFinding.h"

ClRC4KeyFinding::ClRC4KeyFinding(){
	for(int i = 0; i < 5; i++){
		this->m_pCFileHanlder[i] = new FileHandler();
	}

	this->m_pCFileHanlder[0]->loadFile("data/cipher1");
	this->m_pCFileHanlder[1]->loadFile("data/cipher2");
	this->m_pCFileHanlder[2]->loadFile("data/cipher3");
	this->m_pCFileHanlder[3]->loadFile("data/cipher4");
	this->m_pCFileHanlder[4]->loadFile("data/cipher5");
}

ClRC4KeyFinding::~ClRC4KeyFinding(){
	for(int i = 0; i < 5; i++){
		delete(this->m_pCFileHanlder[i]);
	}
}

double ClRC4KeyFinding::getIncidenceOfCoincidence(UINT file1, UINT file2){
	if(file1 < 0 || file1 > 5){
		fprintf(stderr, "File1 value is out of bounds.");
		return -1;
	}

	if(file2 < 0 || file2 > 5){
		fprintf(stderr, "File2 value is out of bounds.");
		return -1;
	}

	char *bufferStream1 = this->m_pCFileHanlder[file1]->getBuffer();
	UINT bufferStream1Size = this->m_pCFileHanlder[file1]->getBufferSize();
	char *bufferStream2 = this->m_pCFileHanlder[file2]->getBuffer();
	UINT bufferStream2Size = this->m_pCFileHanlder[file2]->getBufferSize();
	double  IOC = 0;

	if(bufferStream1Size >= bufferStream2Size){
		for(UINT i = 0; i < bufferStream1Size; i++){
			char temp1 = bufferStream1[i];
			char temp2 = bufferStream2[i];

			if(tolower(temp1) == tolower(temp2)){
				IOC+= (1.0/(double)bufferStream1Size);
			}
		}
	}else{
		for(UINT i = 0; i < bufferStream2Size; i++){
			char temp1 = bufferStream1[i];
			char temp2 = bufferStream2[i];

			if(tolower(temp1) == tolower(temp2)){
				IOC+= (1.0/(double)bufferStream1Size);
			}
		}
	}

	return IOC;
}

int main(int arg0, char** arg1){
	ClRC4KeyFinding *rc = new ClRC4KeyFinding();
	double ioc1_2 = rc->getIncidenceOfCoincidence(0,1);
	double ioc1_3 = rc->getIncidenceOfCoincidence(0,2);
	double ioc1_4 = rc->getIncidenceOfCoincidence(0,3);
	double ioc1_5 = rc->getIncidenceOfCoincidence(0,4);
	double ioc2_3 = rc->getIncidenceOfCoincidence(1,2);
	double ioc2_4 = rc->getIncidenceOfCoincidence(1,3);
	double ioc2_5 = rc->getIncidenceOfCoincidence(1,4);
	double ioc3_4 = rc->getIncidenceOfCoincidence(2,3);
	double ioc3_5 = rc->getIncidenceOfCoincidence(2,4);
	double ioc4_5 = rc->getIncidenceOfCoincidence(3,4);

	printf("Probability: %f\n", ((double)1/(double)256));
	printf("Cipher1 & 2 IOC: %f\n", ioc1_2);
	printf("Cipher1 & 3 IOC: %f\n", ioc1_3);
	printf("Cipher1 & 4 IOC: %f\n", ioc1_4);
	printf("Cipher1 & 5 IOC: %f\n", ioc1_5);
	printf("Cipher2 & 3 IOC: %f\n", ioc2_3);
	printf("Cipher2 & 4 IOC: %f\n", ioc2_4);
	printf("Cipher2 & 5 IOC: %f\n", ioc2_5);
	printf("Cipher3 & 4 IOC: %f\n", ioc3_4);
	printf("Cipher3 & 5 IOC: %f\n", ioc3_5);
	printf("Cipher4 & 6 IOC: %f\n", ioc4_5);
}
